package com.itsen.model.opengl.util;


import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;
import java.util.List;

/**
 * 缓冲区工具类
 */
public class BufferUtil {
    /**
     * 将浮点数组转换成字节缓冲区
     *
     * @param arr
     * @return
     */
    public static ByteBuffer arr2ByteBuffer(float[] arr) {
        ByteBuffer ibb = ByteBuffer.allocateDirect(arr.length * 4);
        ibb.order(ByteOrder.nativeOrder());
        FloatBuffer fbb = ibb.asFloatBuffer();
        fbb.put(arr);
        ibb.position(0);
        return ibb;
    }

    /**
     * @param arr
     * @return
     */
    public static FloatBuffer arr2FloatBuffer(float[] arr) {
        ByteBuffer ibb = ByteBuffer.allocateDirect(arr.length * 4);
        ibb.order(ByteOrder.nativeOrder());
        FloatBuffer fbb = ibb.asFloatBuffer();
        fbb.put(arr);
        fbb.position(0);
        return fbb;
    }

    /**
     * 将短整型数组转换成Short缓冲区
     * @param arr
     * @return
     */
    public static ShortBuffer arr2ShortBuffer(short[] arr){
        ByteBuffer ibb = ByteBuffer.allocateDirect(arr.length*2);
        ibb.order(ByteOrder.nativeOrder());
        ShortBuffer sbb =ibb.asShortBuffer();
        sbb.put(arr);
        sbb.position(0);
        return sbb;
    }
    /**
     * 将list转换成字节缓冲区
     *
     * @param list
     * @return
     */
    public static ByteBuffer list2ByteBuffer(List<Float> list) {
        ByteBuffer ibb = ByteBuffer.allocateDirect(list.size() * 4);
        ibb.order(ByteOrder.nativeOrder());
        FloatBuffer fbb = ibb.asFloatBuffer();
        for (Float f : list) {
            fbb.put(f);
        }
        ibb.position(0);
        return ibb;
    }
}

